package cn.jichangxiu.auth.controller;

import cn.jichangxiu.auth.service.AuthService;
import cn.jichangxiu.common.ucenter.model.AuthToken;
import cn.jichangxiu.common.ucenter.model.RequestLoginData;
import cn.jichangxiu.common.utils.CookieUtils;
import cn.jichangxiu.common.web.model.exception.PreyException;
import cn.jichangxiu.common.web.model.response.R;
import cn.jichangxiu.common.web.model.response.ResponseCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api")
@Api(tags = "用户授权接口")
public class AuthController {

    @Value("${auth.clientId}")
    String clientId;
    @Value("${auth.clientSecret}")
    String clientSecret;
    @Value("${auth.cookieDomain}")
    String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    int cookieMaxAge;

    @Autowired
    private AuthService authService;

    @ApiOperation(value = "login")
    @PostMapping("/login")
    public R login(RequestLoginData requestLoginData){
        if(requestLoginData == null || StringUtils.isEmpty(requestLoginData.getAccount())){
            return new R(ResponseCode.LOGIN_FALL_ACCOUNT_EMPTY);
        }
        if(requestLoginData == null || StringUtils.isEmpty(requestLoginData.getPassword())){
            return new R(ResponseCode.LOGIN_FALL_PASSWORD_EMPTY);
        }
        //账号
        String username = requestLoginData.getAccount();
        //密码
        String password = requestLoginData.getPassword();
        AuthToken authToken = null;
        try {
            authToken = authService.login(username, password, clientId, clientSecret);
        }catch (PreyException e){
            return new R(e.getResultCode());
        }
        if (authToken != null){
            //将令牌存储到cookie
            this.saveCookie(authToken.getAccessToken());
            return new R(ResponseCode.LOGIN_SUCCESS);
        }
        return new R(ResponseCode.LOGIN_FALL);
    }

    /**
     * 将令牌存储到cookie
     * @param token
     */
    private void saveCookie(String token){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //HttpServletResponse response,String domain,String path, String name, String value, int maxAge,boolean httpOnly
        CookieUtils.addCookie(response,cookieDomain,"/","uid",token,cookieMaxAge,false);
    }


}
